<template>
	<div class="system-tabs">
		<div class="tabs-container">
			<div
				v-for="(tab, index) in tabs"
				:key="tab.key"
				class="tab-item"
				:class="{ active: activeTab === tab.path }"
				@click="switchTab(tab)"
			>
				<span>{{ tab.title }}</span>
				<span v-if="tabs.length > 1" class="close-icon" @click.stop="closeTab(tab.path, index)">×</span>
			</div>
		</div>
	</div>
</template>

<script setup>
import './index.scss'
import { useTabsStore } from '@/store/index'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'

const router = useRouter()
const tabsStore = useTabsStore()
const { tabs, activeTab } = storeToRefs(tabsStore)
const switchTab = tab => {
	tabsStore.setActiveTab(tab.path)
	router.push({ path: tab.path, query: tab.query, params: tab.params })
}

const closeTab = (path, index) => {
	tabsStore.closeTab(path)
	if (!tabs.value.length) {
		return router.push('/workSpace') // 如果没有标签了，跳转到首页
	}
	if (activeTab != path) {
		const remainingTab = tabs.value[index == 0 ? 0 : index - 1]
		router.push({ path: remainingTab.path })
	}
}
</script>
